package server;

import control.CControl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import websocket.HttpRequest;
import websocket.WebSocketConnection;

public class SRequestProcessor extends Thread
{
    private final static Logger LOGGER = Logger.getLogger(SRequestProcessor.class
        .getName());
    
    private Socket clientSocket;
    private static final int socketTimeout = 5000;
    private CControl cControl;

    public SRequestProcessor(CControl cControl, Socket clientSocket)
    {
        if (cControl == null || clientSocket == null)
        {
            throw new IllegalArgumentException(
                    "cControl or clientSocket is null");
        }
        this.cControl = cControl;
        this.clientSocket = clientSocket;
    }

    public void run()
    {
        // Read the request from the client
        // Decide what kind of request is this (now only HTTP requests are supported)
        // If it is wrong request then drop connection
        // If it is good request then process it further

        int readByte;
        String readLine;
        try
        {
            clientSocket.setSoTimeout(socketTimeout);

            BufferedReader istream = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
            readLine = istream.readLine();
            if (readLine != null)
            {
                HttpRequest request = new HttpRequest(readLine);
                request.readHeaders(istream);
                LOGGER.log(Level.FINE, "Client {0}:{1} has sent HTTP headers", new Object[]{clientSocket.getInetAddress().toString(), clientSocket.getPort()});
                LOGGER.log(Level.FINEST, "Received headers: {0}", request.toString());
                LOGGER.log(Level.FINEST, "Is client connected? {0}", clientSocket.isConnected());
                WebSocketConnection wsCon = new WebSocketConnection(
                        clientSocket, request);
                LOGGER.finer("Websocket connection is now open. Creating client");
                SClient websocketClient = new SClient(cControl, wsCon);
                LOGGER.finer("Client created");
            }
        }
        catch (IllegalArgumentException | UnsupportedOperationException ex)
        {
            LOGGER.log(Level.INFO, ex.getMessage());
        }
        catch (IOException ex)
        {
            LOGGER.log(Level.WARNING, "There was an IOException while reading from the client stream: {0}", ex.getMessage());
            LOGGER.log(Level.FINE, ex.toString());
        }
    }
}
